来自服务器的java消息未到达客户端
我想知道,当服务器从客户端收到一条消息,该消息是例如“start”时,服务器会发回其余客户端的IP和端口
服务器的一部分:
...
for (i = 0; i < max_clients; i++) {
sd = client_socket[i];
memset(buffer, 0, 10000);
if (FD_ISSET( sd , &readfds)) {
if ((valread = read( sd , buffer, 1024)) == 0) {
getpeername(sd, (struct sockaddr*)&address, (socklen_t*)&addrlen);
printf("Host disconnected , ip %s , port %d \n" ,
inet_ntoa(address.sin_addr) , ntohs(address.sin_port));
close( sd );
client_socket[i] = 0;
}
else {
char cmd[10] = "";
int k;
for(k=0; k<strlen(buffer)-1; k++) {
char tmp[2] = "";
tmp[0] = buffer[k];
strcat(cmd, tmp);
}
if (strcmp(cmd, "start") == 0) {
char clientInfo[1000] = "[ ";
for(j=0; j<max_clients; j++) {
if (client_socket[j] > 0 && client_socket[j] != sd) {
char port[12];
sprintf(port, "%d", clients[j].port);
strcat(clientInfo, "{");
strcat(clientInfo, clients[j].addr);
strcat(clientInfo, " - ");
strcat(clientInfo, port);
strcat(clientInfo, "} ");
}
}
strcat(clientInfo, "]");
send(sd, clientInfo, strlen(clientInfo), 0);
printf("%s\n", clientInfo);
} else {
buffer[valread] = '\0';
for(j=0; j<max_clients; j++) {
int outSock = client_socket[j];
if(outSock != master_socket && outSock != sd) {
send(outSock , buffer , strlen(buffer) , 0 );
}
}
}
}
}
}
...
客户的一部分:
public ChatWindowController() {
try {
clientSocket = new Socket("127.0.0.1", 54000);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
thread = new Thread() {
@Override
public void run() {
try {
while(isRunning) {
if (ta_display != null) {
String message = inFromServer.readLine();
System.out.println(message);
ta_display.appendText(message + '\n');
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
};
thread.start();
} catch(Exception e) {
e.printStackTrace();
}
}
...
...
@FXML
void sendMsg(ActionEvent event) {
String message = tf_user_input.getText();
if (username == null || username.equals("") || username.trim().equals("")) {
ta_display.appendText("You can not send a message, set your username!\n");
return;
}
if (message != null && !message.equals("") && !message.trim().equals("")) {
try {
out.println(username + ": " +message);
out.flush();
} catch(Exception e) {
e.printStackTrace();
}
ta_display.appendText(username + ": " + message + "\n");
}
tf_user_input.setText("");
}
@FXML
void sendFile(ActionEvent event) {
FileChooser fileChooser = new FileChooser();
File file = fileChooser.showOpenDialog(null);
out.println("start");
out.flush();
}
来自客户端的消息被发送到服务器,服务器将它们发送到其他客户端,这样就可以工作了
但是当客户机向服务器发送消息“start”时,我想发回其余客户机的ip和端口,但它不会返回到客户机,只有当其他客户机之一写入内容时,才会出现带有ip和用户端口的消息
例如“[{127.0.0.1-1234}{127.0.0.1}]用户:示例”
就像信息已经丢失,并与另一个一起到达。我打印IP和端口,看看是否一切正常,它打印正确
我没有收到任何错误
有人知道如何在收到客户的特定消息后发回消息吗
共 (0) 个答案